<?php
// +----------------------------------------------------------------------
// | 用户等级
// +----------------------------------------------------------------------
namespace app\common\model;
use think\Model;
use base\other\Strings;

class UserVip extends Model
{
	use \base\model\ModelTrait;
	
	//事件观察
	protected static function init(){
    	self::event('after_insert', function ($data) {
    		model('user')->where('id',$data['uid'])->update([
    			'is_vip'=>1,
    			'usercode'=>$data['code'],
    			'phone'=>$data['phone'],
    			'realname'=>$data['name'],
    			'birthday'=>$data['birthday'],
    			'sex'=>$data['sex']
    		]);
        });
    }
	
	
	//隐藏字段
	protected $hidden = ["password",'id'];
	
	// 自动完成
	protected $insert = ['code'];
	protected function setCodeAttr($value) {
		if($value) return $value;
		return Strings::createOrderNo();
    }
	
	//关联会员表
	public function userInfo(){
        return $this->hasOne('user','id','uid')->bind([
        	'balance',
        	'balance_gift',
        	'brokerage',
        	'integral'
        ]);
    }
    
    //关联等级表
	public function levelInfo(){
        return $this->hasOne('UserLevel','level','level')->bind([
        	'level_name'=>'name',
        	'role_name',
        	'discounts',
        ]);
    }
    
   	/**
    * 验证规则
    */
	protected $rule = [
		'uid|会员'=>'require|integer|unique:UserVip',
		'phone|手机号'=>'require|integer|min:11|max:11|unique:UserVip',
		'name|姓名'=>'require',
		'password|密码'=>'require',
	];
	
	
	//升级
	public function upgradeLevel($uid,$uplevel){
		$userVip = self::where('uid',$uid)->find();
		if($userVip->level < $uplevel){
			$userVip->level = $uplevel;
			$userVip->upgrade_mode = "购买升级商品";
			$userVip->upgrade_time =  date("Y-m-d H:i:s");
			$userVip->save();
		}
		return true;
    }
	
	/**
	* 自动设置等级 - vip会员
	*/
	public function upgrade($uid){
		
		if( !$userVip = self::where('uid',$uid)->find() ) return true;
		
		//已消费
		$y_consume = model('order')
			->where('uid',$uid)
			->where('is_pay',1)
			->where('pay_type','<>','brokerage')
			//->where('status','>=',0)
			->sum('pay_price');
			
		//可升等级	
		$userLevel = model('UserLevel')
			->where('role_id',1)
			->where('consume_total','<=',$y_consume)
			->order("consume_total",'desc')
			->find();
		
		$userVip->level =  $userVip->level < $userLevel->level ? $userLevel->level : $userVip->level;
		$userVip->upgrade_mode =  "业绩达标";
		$userVip->upgrade_time =  date("Y-m-d H:i:s");
		$userVip->save();
		
		return true;
	}
		
}
